package com.wuye.controller;

import com.wuye.model.Order;
import com.wuye.model.OrderDetail;
import com.wuye.model.OrderItem;
import com.wuye.repository.OrderItemRepository;
import com.wuye.repository.OrderRepository;
import com.wuye.service.OrderService;
import com.wuye.web.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by jiawenlong on 2016/6/8.
 */
@RestController
@RequestMapping("/admin/order")
public class OrderAdminController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private OrderItemRepository orderItemRepository;
    private Log log = LogFactory.getLog(this.getClass());

    @RequestMapping("/orderExport.jspx")
    public void orderExport(HttpServletRequest request, HttpServletResponse resp,
                            @RequestParam(value = "begin", defaultValue = "") String begin,
                            @RequestParam(value = "end", defaultValue = "") String end,
                            @RequestParam(value = "state", defaultValue = "") String state) throws IOException {
        if (StringUtils.isEmpty(begin) || StringUtils.isEmpty(end)) return;
        resp.setHeader("Content-Type", "application/octet-stream; charset=utf-8");
        OutputStream os = resp.getOutputStream();

        try {
            String name = "物业餐厅订单列表_" + begin.replace("-", "").replace(":", "").replace(" ", "") + "_" + end.replace("-", "").replace(":", "").replace(" ", "");
            log.info(name);
            int rowNum = 0;
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet(name);
            begin = begin + " 00:00:00";
            end = end + " 23:59:59";
            if (state.equals("") || state.equals("1")) {
                state = "";
            } else {
                for (OrderState item : OrderState.values()) {
                    if (state.equals(item.getState())) {
                        state = item.name();
                        break;
                    }
                }
            }
            List<Order> orders = orderRepository.findByOrderDateAndState(begin, end, state);
            List<OrderDetail> ods = new ArrayList<OrderDetail>();
            for (Order o : orders) {
                OrderDetail od = new OrderDetail(o);
                List<OrderItem> orderItems = orderItemRepository.findByOrderSn(o.getOrderNum());
                od.setOrderItems(orderItems);
                ods.add(od);
            }
            if (ods.size() > 0) {
                HSSFFont font = wb.createFont();
                font.setBold(true);
                font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
                HSSFCellStyle style = wb.createCellStyle();
                style.setFont(font);
                HSSFRow row = sheet.createRow(rowNum++);
                row.createCell(0, 1).setCellValue("国投物业一分公司餐厅订单");
                row = sheet.createRow(rowNum++);
                String[] names = {"序号", "订单编号", "下单菜品", "订单状态", "联系方式",
                        "下单时间", "付款金额", "交易方式", "用户备注", "用户签名", "备注"};
                for (int i = 0; i < names.length; i++) {
                    row.createCell(i, 1).setCellValue(names[i]);
                }
                row.setRowStyle(style);
                int a = 1;
                for (OrderDetail objects : ods) {
                    HSSFRow itemRow = sheet.createRow(rowNum++);
                    itemRow.createCell(0, 1).setCellValue(a);
                    itemRow.createCell(1, 1).setCellValue(objects.getOrderNum());
                    String orderItemStr = "";
                    for (OrderItem oi : objects.getOrderItems()) {
                        orderItemStr += oi.getItemName() + "  " + "×" + oi.getAmount() + "\r\n";
                    }
                    itemRow.createCell(2, 1).setCellValue(orderItemStr);
                    itemRow.createCell(3, 1).setCellValue(objects.getOrderState());
                    itemRow.createCell(4, 1).setCellValue(objects.getUserName() + "  " + objects.getCellPhone());
                    itemRow.createCell(5, 1).setCellValue(objects.getOrderDate());
                    itemRow.createCell(6, 1).setCellValue(objects.getTotalPrice());
                    itemRow.createCell(7, 1).setCellValue(objects.getPayMethod());
                    itemRow.createCell(8, 1).setCellValue(objects.getMemo());
                    itemRow.createCell(9, 1).setCellValue("");
                    itemRow.createCell(10, 1).setCellValue("");
                    a++;
                }
            }
            resp.addHeader("Content-Disposition", "attachment; filename=" + new String(name.getBytes(), "iso-8859-1") + ".xls");
            wb.write(os);
            wb.close();
        } catch (Exception e) {
            e.printStackTrace();
            resp.addHeader("Content-Disposition", "attachment; filename*=UTF-8''error.txt");
            os.write("出错了，请重试".getBytes());
            os.write(e.getMessage().getBytes());
        }
        os.flush();
        os.close();
    }

    @RequestMapping("/financeExport.jspx")
    public void financeExport(HttpServletRequest request, HttpServletResponse resp,
                              @RequestParam(value = "begin", defaultValue = "") String begin,
                              @RequestParam(value = "end", defaultValue = "") String end) throws IOException {
        if (StringUtils.isEmpty(begin) || StringUtils.isEmpty(end)) return;
        resp.setHeader("Content-Type", "application/octet-stream; charset=utf-8");
        OutputStream os = resp.getOutputStream();

        try {
            String name = "财务流水_" + begin.replace("-", "").replace(":", "").replace(" ", "") + "_" + end.replace("-", "").replace(":", "").replace(" ", "");
            log.info(name);
            int rowNum = 0;
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet(name);
            begin = begin + " 00:00:00";
            end = end + " 23:59:59";

            List<Order> orders = orderRepository.findOrdAllByOrderByOrderDate_Desc(begin, end);
            if (orders.size() > 0) {
                HSSFFont font = wb.createFont();
                font.setBold(true);
                font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
                HSSFCellStyle style = wb.createCellStyle();
                style.setFont(font);
                HSSFRow row = sheet.createRow(rowNum++);
                row.createCell(0, 1).setCellValue("国投物业一分公司财务流水");
                row = sheet.createRow(rowNum++);
                String[] names = {"序号", "订单编号", "下单日期", "交易金额", "交易状态", "用户账号", "支付方式"};
                for (int i = 0; i < names.length; i++) {
                    row.createCell(i, 1).setCellValue(names[i]);
                }
                row.setRowStyle(style);
                int a = 1;
                for (Order objects : orders) {
                    HSSFRow itemRow = sheet.createRow(rowNum++);
                    itemRow.createCell(0, 1).setCellValue(a);
                    itemRow.createCell(1, 1).setCellValue(objects.getOrderNum());
                    itemRow.createCell(2, 1).setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(objects.getOrderDate()));
                    itemRow.createCell(3, 1).setCellValue(objects.getTotalPrice());
                    String stat = "";
                    for (OrderState o : OrderState.values()) {
                        if (o.toString().equals(objects.getOrderState())) {
                            stat = o.getState();
                            break;
                        }
                    }
                    itemRow.createCell(4, 1).setCellValue(stat);
                    itemRow.createCell(5, 1).setCellValue(objects.getUserName() + "  " + objects.getCellPhone());
                    String pays = "";
                    for (PayMethod p : PayMethod.values()) {
                        if (p.toString().equals(objects.getPayMethod())) {
                            pays = p.getPayMethod();
                            break;
                        }
                    }
                    itemRow.createCell(6, 1).setCellValue(pays);
                    a++;
                }
            }
            resp.addHeader("Content-Disposition", "attachment; filename=" + new String(name.getBytes(), "iso-8859-1") + ".xls");
            wb.write(os);
            wb.close();
        } catch (Exception e) {
            e.printStackTrace();
            resp.addHeader("Content-Disposition", "attachment; filename*=UTF-8''error.txt");
            os.write("出错了，请重试".getBytes());
            os.write(e.getMessage().getBytes());
        }
        os.flush();
        os.close();
    }
}
